package other.example;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;

/**
 * @author bingo
 * @Description
 * @Date 2018/6/25
 */
public class ValidateCode {

    private int weight;

    private int height;

    private int codeCount;

    private int fontHeight;

    private int codeX;

    private int codeY;

    private BufferedImage bufferedImage;

    char[] codeSquence = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".toCharArray();

    public ValidateCode(int weight, int height, int codeCount) {

        this.weight = weight;

        this.height = height;

        this.codeCount = codeCount;

        this.fontHeight = height-2;

        this.codeX = weight / (codeCount+2);

        this.codeY = height-4;

        bufferedImage = new BufferedImage(weight,height,BufferedImage.TYPE_3BYTE_BGR);
        Graphics2D graphics2D = bufferedImage.createGraphics();
        graphics2D.setColor(Color.white);
        graphics2D.fillRect(0,0,weight,height);
        Font font = new Font("", Font.BOLD, fontHeight);
        graphics2D.setFont(font);
        graphics2D.setColor(Color.magenta);
        graphics2D.drawRect(0,0,weight-1,height-1);

        Random random = new Random();
        for(int i=0;i<6;i++){
            int x = random.nextInt(weight);
            int y = random.nextInt(height);
            int x1 = random.nextInt(20);
            int y1 = random.nextInt(20);
          /*  int x = (i+1)*codeX;
            int y = 0;
            int x1 = x;
            int y1 = 300;*/
            graphics2D.drawLine(x,y,x1,y1);
            }

         for(int i=0;i<codeCount;i++){

             String s = String.valueOf(codeSquence[random.nextInt(codeSquence.length)]);
             graphics2D.drawString(s,codeX*(i+1),codeY);
         }
        try {
            File file = new File("D:/2.png");
            FileOutputStream fis = new FileOutputStream(file);
            ImageIO.write(bufferedImage,"png",fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {

        ValidateCode validateCode = new ValidateCode(1600,300,5);
    }
}
